package com.huike.game.DbHelper;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.huike.game.base.Bean20;
import com.huike.game.base.Game11;
import com.huike.game.base.Game15;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class DataHelper extends OrmLiteSqliteOpenHelper {

    public static DataHelper instance;
    public static synchronized DataHelper getInstance(Context context){
        if(instance == null){
            synchronized (DataHelper.class){
                if(instance == null){
                    instance = new DataHelper(context);
                }
            }
        }
        return  instance;
    }

    private Map<String,Dao> maps = new HashMap<>();
    public  synchronized Dao getDao(Class cls) throws SQLException {
        Dao dao = null;
        String name = cls.getSimpleName();
        if(maps.containsKey(name)){
            dao = maps.get(name);
        }

        if(dao == null){
            dao = super.getDao(cls);
            maps.put(name,dao);
        }
        return  dao;
    }

    public void close(){
        super.close();
        for (String key:
             maps.keySet()) {
            Dao dao = maps.get(key);
            dao = null;
        }

    }

    public DataHelper(Context context) {
        super(context, "my.db", null, 2);
    }



    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, Game15.DataBean.class);
            TableUtils.createTable(connectionSource, Game11.DataBean.class);
            TableUtils.createTable(connectionSource,Bean20.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {
        try {
            TableUtils.dropTable(connectionSource,Game15.DataBean.class,true);
            TableUtils.dropTable(connectionSource,Game11.DataBean.class,true);
            TableUtils.dropTable(connectionSource,Bean20.class,true);
            onCreate(sqLiteDatabase,connectionSource);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
